/*
	
	使用multipleStatements属性，同时执行多条语句
	
*/


var mysql = require('mysql');
var tableName = "users";
var connection = mysql.createConnection({
	host: 'localhost',
	port: 3306,
	database: 'test',
	multipleStatements: true,
	user: 'root',
	password: '123456'
});


connection.connect(function(err){
	if(err)
		console.log("连接失败");
	else{
		console.log("连接成功");
		insertData();
	}
});

function insertData(){
	var sqlStr = "";
	for(var i=0; i<4; i++){
		sqlStr += 'insert into ' + tableName + " (userName, passWord) values(" 
			+ connection.escape("用户名" + i.toString()) + ", "
			+ connection.escape("密码" + i.toString()) + ");";
	}
	// console.log(sqlStr);
	connection.query(sqlStr, function(err, result){
		if(err)
			console.log("insert 失败");
		else
			updateData();
	});
	
}

function updateData(){
	connection.query('update ' + tableName + ' set passWord = ? where userName = ?', ["密码xxx", "用户名2"], function(err, result){
		if(err)
			console.log("update 失败");
		else
			deleteData();
	});
}

function deleteData(){
	connection.query('delete from ' + tableName + ' where userName=?', ["用户名3"], function(err, result){
		if(err)
			console.log("delete 失败");
		else
			queryData();
	});
}

function queryData(){
	connection.query('select * from ' + tableName, function(err, result){
		if(err)
			console.log("query 失败");
		else{
			console.log(result);
			connection.end();
		}
	});
}


